<?php
class Tool extends ActiveRecord\Model{
	
  var $password = FALSE;
  

  
  function set_password($plaintest)
  {
    $this->hashed_password = $this->hash_password($plaintext);
  }
  
  private function hash_password($password)
  {
      $salt = bin2hex(mcrypt_create_iv(32,MCRYPT_DEV_URANDOM));
      $hash = hash('sha256',$salt.$password);
      
      return $salt.$hash;
  }
  
  private function validate_password($password)
  {
      $salt = substr($this->hashed_password, 0 , 64);
      $hash = substr($this->hashed_password, 64, 64);
      
      $password_hash = hash('sha256', $salt.$password);
      
      return $password_hash == $hash;
  }
  
  public static function validate_login($username,$password)
  {
      $tool = tool::find_by_username($username);
      
      if($tool && $tool->validate_password($password))
      {
      
      	    tool::login($tool->id);
      		return $tool;
      }
          
      else
          return FALSE;
  }
  
  public static function login($tool_id)
  {
      $CI =& get_instance();
      $CI->session->set_userdata('tool_id',$tool_id);
  }
  
  public static function logout()
 {	
 		$CI =& get_instance();
 		$CI->session->sess_destroy();
 	    redirect ('tool/login');
 
 }
	
}